<?php
namespace Common\Tool;

class Excelexport
{
	public $header = "<?xml version=\"1.0\" encoding=\"GB2312\"?\>
<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" 
 xmlns:x=\"urn:schemas-microsoft-com:office:excel\" 
 xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" 
 xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
    public $footer = "</Workbook>";
    public $lines = array ();
    public $worksheet_title = "Table1";

    public function addRow($array)
    {
		$cells = "";
		foreach ($array as $k => $v){
			if(is_numeric($v)) {
				if(substr($v, 0, 1) == 0) {
					$cells .= "<Cell><Data ss:Type=\"String\">".$v."</Data></Cell>\n";
				} else {
					$cells .= "<Cell><Data ss:Type=\"Number\">".$v."</Data></Cell>\n";
				}
			} else {
				$cells .= "<Cell><Data ss:Type=\"String\">".iconv("UTF-8","GB2312//IGNORE",$v)."</Data></Cell>\n";
			}
		}
		$this->lines[] = "<Row>\n".$cells."</Row>\n";
	}

    public function addArray($array)
    {
		foreach ($array as $k => $v){
			$this->addRow($v);
		}
	}

    public function setWorksheetTitle($title)
    {
		$title = preg_replace ("/[\\\|:|\/|\?|\*|\[|\]]/", "", $title);
		$title = substr($title, 0, 31);
		$this->worksheet_title = $title;
	}

    public function generateXML($filename)
    {
		header("Content-Type:application/vnd.ms-excel;charset=GB2312");
		header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");
		echo stripslashes ($this->header);
		echo "\n<Worksheet ss:Name=\"" . $this->worksheet_title . "\">\n<Table>\n";
		echo "<Column ss:Index=\"1\" ss:AutoFitWidth=\"0\" ss:Width=\"110\"/>\n";
		echo implode ("\n", $this->lines);
		echo "</Table>\n</Worksheet>\n";
		echo $this->footer;

	}
}
/*用法*/
/*
单元格内换行符为：$SpecialChar = '&#10;';
$doc = array (
array ('中国', '中国人', '中国人民', '123456',"asdfasdf\t\nasdfasdf\n\nasdfasdf\n"),
array ('中国', '中国人', '中国人民', '123456',"asdfasdf\t\nasdfasdf\n\nasdfasdf\n"),
array ('中国', '中国人', '中国人民', '123456',"asdfasdf\t\nasdfasdf\n\nasdfasdf\n"),
);
$xls = new Excel;
$xls->addArray ( $doc );
$xls->generateXML ("mytest");
*/